<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :sm="24" :md="24" :xxl="16">
            <a-form-item label="区域">
              <a-row :gutter="5" type="flex">
                <a-col :span="6">
                  <a-select
                    placeholder="省"
                    v-model="queryParam.provinceCode"
                    @change="e => addressChange(e, 'cityOptions', 'province')"
                  >
                    <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="市"
                    v-model="queryParam.cityCode"
                    @change="e => addressChange(e, 'areaOptions', 'city')"
                  >
                    <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="区"
                    v-model="queryParam.areaCode"
                    @change="e => addressChange(e, 'streetOptions', 'area')"
                  >
                    <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="街道"
                    v-model="queryParam.streetCode"
                    @change="e => addressChange(e, '', 'street')"
                  >
                    <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-item label="用户账号">
              <a-input placeholder="请输入" v-model="queryParam.username"></a-input>
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus">
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="商家名称">
                <a-input placeholder="请输入" v-model="queryParam.realname"></a-input>
              </a-form-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="账户状态">
                <j-dict-select-tag allowClear v-model="queryParam.delFlag" placeholder="请选择" dictCode="delFlag" />
              </a-form-item>
            </a-col>

            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="代理商状态">
                <j-dict-select-tag
                  allowClear
                  v-model="queryParam.agentStatus"
                  placeholder="请选择"
                  dictCode="agentStatus"
                />
              </a-form-item>
            </a-col>

            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="创建时间"><a-range-picker class="per100"/></a-form-item>
            </a-col>

            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="所属公司">
                <a-select v-model="queryParam.companyId" placeholder="请选择">
                  <a-select-option v-for="item in companyOptions" :key="item.id" :value="item.id">
                    {{ item.companyName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>

          <a-col :sm="24" :md="12" :xl="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button @click="searchReset({ agentType: 2 })" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator mt10">
      <a-button type="success" icon="plus" @click="handleAdd()">新增</a-button>
    </div>

    <!-- table区域 -->
    <a-table
      ref="table"
      bordered
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <span slot="action" slot-scope="text, record">
        <a-button type="link" class="ml5 mr5" size="small" @click="handleDetail(record.id)">详情</a-button>
        <a-button type="primary" class="ml5 mr5" size="small" @click="handleUpdate(record.id, 'edit')">编辑</a-button>
        <a-button type="success" class="ml5 mr5" size="small" @click="showModal(record, 'ResetPasswordRef')"
          >重置密码</a-button
        >
        <a-button
          type="danger"
          class="ml5 mr5"
          size="small"
          v-if="parseInt(record.status) === 1"
          @click="updateAccountStatus(record.id, '2')"
          >冻结</a-button
        >
        <a-button
          type="primary"
          class="ml5 mr5"
          size="small"
          v-if="parseInt(record.status) === 2"
          @click="updateAccountStatus(record.id, '1')"
          >解冻</a-button
        >
        <a-button type="orange" class="ml5 mr5" size="small" @click="cancelUser(record.id)">注销</a-button>
      </span>
    </a-table>

    <!-- 重置密码 -->
    <reset-password ref="ResetPasswordRef" @ok="loadData()"></reset-password>
    <merchant-add ref="MerchantAddRef" @ok="loadData()"></merchant-add>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Api from '@/api/AgentManage/AgentManage'
import { filterDictText, initDictOptions } from '@comp/dict/JDictSelectUtil'
import ResetPassword from '@views/AgentManage/Modal/ResetPassword'
import { frozenBatch } from '@/api/api'
import { getAction } from '@api/manage'
import AgentManage from '@/api/AgentManage/AgentManage'
import MerchantAdd from '@views/AgentManage/Modal/MerchantAdd'
import CommonApi from '@api/Common'

export default {
  name: 'MerchantManage',
  mixins: [JeecgListMixin],
  components: { ResetPassword, MerchantAdd },
  data() {
    return {
      url: {
        list: Api.list,
        cancel: AgentManage.cancel
      },
      accountStatusOptions: [],
      agentStatusOptions: [],
      companyOptions: [],
      columns: [],
      queryParam: {
        agentType: 2
      }
    }
  },
  created() {
    this.columns = [
      {
        title: '用户账号',
        dataIndex: 'username',
        width: 120,
        align: 'center',
        sorter: (a, b) => {
          return a.username - b.username
        }
      },
      {
        title: '商家ID',
        dataIndex: 'id',
        align: 'center',
        sorter: (a, b) => {
          return a.id - b.id
        }
      },
      {
        title: '商家姓名',
        dataIndex: 'realname',
        align: 'center',
        sorter: (a, b) => {
          return a.realname - b.realname
        }
      },
      {
        title: '上级代理姓名',
        align: 'center',
        dataIndex: 'parentAgentName'
      },
      {
        title: '所属公司',
        dataIndex: 'companyName',
        align: 'center'
      },
      {
        title: '手机号码',
        align: 'center',
        dataIndex: 'phone',
        sorter: (a, b) => {
          return a.phone - b.phone
        }
      },
      {
        title: '区域',
        align: 'center',
        customRender(text, record, index) {
          return ['provinceCn', 'cityCn', 'areaCn', 'streetCn']
            .filter(field => record[field])
            .map(field => record[field])
            .reduce((pre, cur) => pre + cur, '')
        },
        sorter: (a, b) => {
          return a.provinceCn - b.provinceCn
        }
      },
      {
        title: '加盟时间',
        align: 'center',
        dataIndex: 'joinData',
        sorter: (a, b) => {
          return a.joinData - b.joinData
        }
      },
      {
        title: '创建时间',
        align: 'center',
        dataIndex: 'createTime',
        sorter: (a, b) => {
          return a.createTime - b.createTime
        }
      },
      {
        title: '账户状态',
        dataIndex: 'status',
        align: 'center',
        sorter: (a, b) => {
          return a.status - b.status
        },
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.accountStatusOptions, text)
        }
      },
      {
        title: '商家状态',
        dataIndex: 'agentStatus',
        align: 'center',
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.agentStatusOptions, text)
        },
        sorter: (a, b) => {
          return a.agentStatus - b.agentStatus
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        fixed: 'right',
        width: 340
      }
    ]
    this.initDictConfig()
    this.getAddress('provinceOptions')
    this.getCompanyList()
  },
  methods: {
    initDictConfig() {
      //初始化字典 - 商家状态
      initDictOptions('agentStatus').then(res => {
        if (res.success) {
          this.agentStatusOptions = res.result
        }
      })

      //初始化字典 - 账户状态
      initDictOptions('status').then(res => {
        if (res.success) {
          this.accountStatusOptions = res.result
        }
      })
    },

    getCompanyList() {
      getAction(CommonApi.companyList).then(res => {
        if (res.code === 200) {
          this.companyOptions = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 创建时间改变
    timeChange(e, arr) {
      if (arr[0]) {
        this.queryParam.startTime = arr[0]
        this.queryParam.endTime = arr[1]
      } else {
        this.queryParam.startTime = undefined
        this.queryParam.endTime = undefined
      }
    },

    showModal(record, name) {
      this.$refs[name].showModal(record)
    },

    updateAccountStatus(id, status) {
      frozenBatch({ ids: id, status: status }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    cancelUser(id) {
      let that = this
      this.$confirm({
        title: '注销账号',
        content: '确认注销此账号吗？',
        onOk: () => {
          getAction(that.url.cancel + id).then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      })
    },

    handleDetail(id, action) {
      this.$router.push(`/agentManage/merchantDetail?id=${id}`)
    },
    // 编辑
    handleUpdate(id, action) {
      let key = action
      if (id) {
        key += `?id=${id}`
      }
      this.$router.push(`/agentManage/merchantUpdate/${key}`)
    },

    handleAdd() {
      this.$refs.MerchantAddRef.showModal()
    }
  }
}
</script>

<style scoped></style>

